<!DOCTYPE html>
<html>
<head>
  <title>📦 订单列表</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <style>
    :root {
      --primary-color: #4361ee;
      --secondary-color: #3f37c9;
      --success-color: #4cc9f0;
      --info-color: #4895ef;
      --warning-color: #f72585;
      --danger-color: #e63946;
      --light-color: #f8f9fa;
      --dark-color: #212529;
      --pending-color: #FF9800;
      --processing-color: #2196F3;
      --completed-color: #4CAF50;
      --cancelled-color: #F44336;
      --refunded-color: #9E9E9E;
      --on-hold-color: #9C27B0;
      --failed-color: #607D8B;
      --muted-color: #6c757d;
      --row-even-bg: #f8f9fa;
      --row-odd-bg: #ffffff;
    }
    
    body {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      min-height: 100vh;
      max-width: 1440px;
      margin: 0 auto;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .header-gradient {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      color: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.15);
      margin-bottom: 25px;
      padding: 25px;
    }
    
    .card {
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
      border: none;
      margin-bottom: 25px;
      transition: all 0.3s;
    }
    
    .card:hover {
      box-shadow: 0 15px 40px rgba(0,0,0,0.15);
      transform: translateY(-3px);
    }
    
    .status-card {
      border-radius: 12px;
      transition: all 0.3s ease;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      height: 100%;
    }
    
    .status-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 30px rgba(0,0,0,0.2);
    }
    
    .table-container {
      background: white;
      border-radius: 15px;
      overflow: hidden;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
    }
    
    .table th {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      color: white;
      font-weight: 600;
      padding: 15px;
    }
    
    .table td {
      padding: 15px;
      vertical-align: middle;
    }
    
    /* 交替行颜色 */
    .table-striped tbody tr:nth-of-type(even) {
      background-color: var(--row-even-bg);
    }
    
    .table-striped tbody tr:nth-of-type(odd) {
      background-color: var(--row-odd-bg);
    }
    
    .table-hover tbody tr:hover {
      background-color: #e9f7fe;
      transform: scale(1.01);
      transition: all 0.2s;
    }
    
    .badge-pending {
      background-color: var(--pending-color) !important;
    }
    
    .badge-processing {
      background-color: var(--processing-color) !important;
    }
    
    .badge-completed {
      background-color: var(--completed-color) !important;
    }
    
    .badge-cancelled {
      background-color: var(--cancelled-color) !important;
    }
    
    .badge-refunded {
      background-color: var(--refunded-color) !important;
    }
    
    .badge-on-hold {
      background-color: var(--on-hold-color) !important;
    }
    
    .badge-failed {
      background-color: var(--failed-color) !important;
    }
    
    .badge-muted {
      background-color: var(--muted-color) !important;
    }
    
    .btn-gradient {
      background: linear-gradient(120deg, var(--primary-color), var(--info-color));
      border: none;
      color: white;
      font-weight: 600;
      padding: 10px 20px;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3);
    }
    
    .btn-gradient:hover {
      background: linear-gradient(120deg, var(--secondary-color), var(--primary-color));
      color: white;
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(67, 97, 238, 0.4);
    }
    
    .btn-success {
      background: linear-gradient(120deg, #28a745, #20c997);
      border: none;
      color: white;
      font-weight: 600;
      padding: 10px 20px;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
    }
    
    .btn-success:hover {
      background: linear-gradient(120deg, #20c997, #28a745);
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(40, 167, 69, 0.4);
    }
    
    .search-card {
      background: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
      padding: 25px;
      margin-bottom: 25px;
    }
    
    .form-control, .form-select {
      height: 46px;
      border: 1px solid #dee2e6;
      border-radius: 8px;
      padding: 10px 15px;
      transition: all 0.3s;
    }
    
    .form-control:focus, .form-select:focus {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.15);
      outline: none;
    }
    
    .input-group-text {
      background: #e9ecef;
      border: 1px solid #dee2e6;
      border-radius: 8px 0 0 8px;
      color: #495057;
      min-width: 45px;
      text-align: center;
    }
    
    .sync-info {
      background: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
      padding: 20px;
      margin-bottom: 25px;
    }
    
    .pagination .page-link {
      color: var(--primary-color);
      border: 1px solid #dee2e6;
      transition: all 0.3s;
    }
    
    .pagination .page-link:hover {
      background-color: var(--primary-color);
      color: white;
      border-color: var(--primary-color);
    }
    
    .pagination .active .page-link {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }
    
    .order-card {
      cursor: pointer;
      transition: all 0.2s;
    }
    
    .order-card:hover {
      background-color: #e9f7fe !important;
    }
    
    .tracking-badge {
      font-size: 0.85rem;
      padding: 5px 10px;
    }
    
    .status-stat-card {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 12px;
      transition: all 0.3s ease;
      height: 100%;
    }
    
    .status-stat-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 30px rgba(0,0,0,0.2);
    }
    
    .nav-link {
      color: rgba(255, 255, 255, 0.8) !important;
      font-weight: 500;
      transition: all 0.3s;
      border-radius: 5px;
      margin: 0 5px;
    }
    
    .nav-link:hover, .nav-link.active {
      color: white !important;
      background-color: rgba(255, 255, 255, 0.1);
    }
    
    .dropdown-toggle::after {
      margin-left: 0.5em;
    }
    
    .filter-clear-btn {
      background: linear-gradient(120deg, #6c757d, #495057);
      border: none;
      color: white;
      font-weight: 600;
      padding: 10px 20px;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
    }
    
    .filter-clear-btn:hover {
      background: linear-gradient(120deg, #495057, #6c757d);
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
    }
    
    /* 商品信息列样式 */
    .product-info-column {
      width: 200px; /* 增加宽度 */
      font-size: 0.85rem; /* 缩小字体 */
    }
    
    .product-info-column small {
      font-size: 0.8rem; /* 进一步缩小字体 */
    }
  </style>
</head>
<body class="p-4">
  <div class="container-fluid">
    <div class="header-gradient">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h1 class="mb-0"><i class="fas fa-boxes me-3"></i>📦 订单中心（共 {{ total_orders }} 个订单）</h1>
          <p class="mb-0 opacity-75">管理所有订单信息</p>
        </div>
        <div class="d-flex align-items-center">
          <nav class="navbar navbar-expand navbar-dark me-4">
            <div class="navbar-nav">
              <a class="nav-link" href="/"><i class="fas fa-home me-1"></i> 系统首页</a>
              <a class="nav-link active" href="/orders"><i class="fas fa-list me-1"></i> 订单管理</a>
              <a class="nav-link" href="/customers"><i class="fas fa-users me-1"></i> 客户管理</a>
              {% if current_user and current_user.role == "root" %}
              <a class="nav-link" href="/users"><i class="fas fa-user-cog me-1"></i> 用户管理</a>
              {% endif %}
            </div>
          </nav>
          <div class="text-end">
            <div>
              {% if can_add_order %}
              <a href="/add-order" class="btn btn-success me-2">
                <i class="fas fa-plus-circle me-1"></i> 添加订单
              </a>
              {% endif %}
              <div class="btn-group">
                <button type="button" class="btn btn-light dropdown-toggle" data-bs-toggle="dropdown">
                  <i class="fas fa-file-export me-1"></i> 导出订单
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li><a class="dropdown-item" href="/export">全部订单</a></li>
                  <li><hr class="dropdown-divider"></li>
                  {% for source in unique_sources[:10] %}
                    <li><a class="dropdown-item" href="/export?source={{ source }}">{{ source }}</a></li>
                  {% endfor %}
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 搜索和筛选功能 -->
    <div class="search-card">
      <h5 class="mb-4"><i class="fas fa-filter me-2"></i>筛选条件</h5>
      <form id="searchForm" class="row g-3">
        <div class="col-md-3">
          <label for="searchOrderId" class="form-label">订单ID</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-hashtag"></i></span>
            <input type="text" class="form-control" id="searchOrderId" placeholder="搜索订单ID" oninput="filterOrders()">
          </div>
        </div>
        <div class="col-md-2">
          <label for="searchCountry" class="form-label">国家</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-flag"></i></span>
            <select class="form-select" id="searchCountry" onchange="filterOrders()">
              <option value="">所有国家</option>
              {% for country in unique_countries %}
                <option value="{{ country }}">{{ country | country_name }}</option>
              {% endfor %}
            </select>
          </div>
        </div>
        <div class="col-md-2">
          <label for="searchSource" class="form-label">来源站点</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-globe"></i></span>
            <select class="form-select" id="searchSource" onchange="filterOrders()">
              <option value="">所有站点</option>
              {% for source in unique_sources[:10] %}
                <option value="{{ source }}">{{ source }}</option>
              {% endfor %}
            </select>
          </div>
        </div>
        <div class="col-md-3">
          <label for="searchStatus" class="form-label">订单状态</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-tasks"></i></span>
            <select class="form-select" id="searchStatus" onchange="filterOrders()">
              <option value="">所有状态</option>
              <option value="processing">待处理</option>
              <option value="completed">已完成</option>
              <option value="cancelled">已取消</option>
              <option value="refunded">已退款</option>
              <option value="on-hold">发货中</option>
              <option value="failed">被拒收</option>
            </select>
          </div>
        </div>
        <div class="col-md-2 d-flex align-items-end">
          <button type="button" class="filter-clear-btn w-100" onclick="clearFilter()">
            <i class="fas fa-broom me-1"></i> 清除筛选
          </button>
        </div>
      </form>
    </div>

    <div class="sync-info">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <strong><i class="fas fa-sync-alt me-2"></i>最后同步时间：</strong>
          {% if last_sync %}
            <span class="text-success fw-bold">{{ last_sync.strftime('%Y-%m-%d %H:%M') }}</span>
          {% else %}
            <span class="text-muted">从未同步</span>
          {% endif %}
        </div>
        <button type="button" class="btn btn-gradient" onclick="syncOrders()">
          <i class="fas fa-sync me-1"></i> 手动同步
        </button>
      </div>
    </div>

    <!-- 状态统计 -->
    <div class="row mb-4">
      {% for stat in status_stats %}
      <div class="col-md-2 col-6 mb-4">
        <div class="status-stat-card p-3 rounded text-center shadow-sm">
          <div class="fs-2 fw-bold">{{ stat.count }}</div>
          <div class="small">
            {% if stat.status == 'processing' %}
              <i class="fas fa-clock me-1"></i> 待处理
            {% elif stat.status == 'completed' %}
              <i class="fas fa-check-circle me-1"></i> 已完成
            {% elif stat.status == 'cancelled' %}
              <i class="fas fa-times-circle me-1"></i> 已取消
            {% elif stat.status == 'refunded' %}
              <i class="fas fa-undo me-1"></i> 已退款
            {% elif stat.status == 'on-hold' %}
              <i class="fas fa-pause-circle me-1"></i> 发货中
            {% elif stat.status == 'failed' %}
              <i class="fas fa-exclamation-triangle me-1"></i> 被拒收
            {% else %}
              {{ stat.status }}
            {% endif %}
          </div>
        </div>
      </div>
      {% endfor %}
    </div>

    <!-- 订单列表 -->
    <div class="table-container">
      <table class="table table-striped table-hover mb-0">
        <thead>
          <tr>
            <th class="text-center" style="width: 100px;">订单编号</th>
            <th class="text-center" style="width: 150px;">订单状态</th>
            <th>客户信息</th>
            <th class="text-center product-info-column">商品信息</th>
            <th class="text-center" style="width: 80px;">数量</th>
            <th class="text-end" style="width: 120px;">订单金额</th>
            <th class="text-center" style="width: 120px;">下单时间</th>
            <th style="width: 120px;">来源站点</th>
          </tr>
        </thead>
        <tbody>
          {% for order in orders %}
          <tr class="order-card" onclick="window.location.href='/order/{{ order.id }}'">
            <td class="text-center product-info-column">
              <strong>#{{ order.order_id }}</strong>
            </td>
            <td class="text-center product-info-column">
              {% if order.status == 'processing' %}
                <span class="badge badge-pending"><i class="fas fa-clock me-1"></i> 待处理</span>
              {% elif order.status == 'completed' %}
                <span class="badge badge-completed"><i class="fas fa-check-circle me-1"></i> 已完成</span>
              {% elif order.status == 'cancelled' %}
                <span class="badge badge-cancelled"><i class="fas fa-times-circle me-1"></i> 已取消</span>
              {% elif order.status == 'refunded' %}
                <span class="badge badge-refunded"><i class="fas fa-undo me-1"></i> 已退款</span>
              {% elif order.status == 'on-hold' %}
                <span class="badge badge-on-hold"><i class="fas fa-pause-circle me-1"></i> 发货中</span>
              {% elif order.status == 'failed' %}
                <span class="badge badge-failed"><i class="fas fa-exclamation-triangle me-1"></i> 被拒收</span>
              {% else %}
                <span class="badge bg-secondary">{{ order.status }}</span>
              {% endif %}
              <!-- 显示物流信息 -->
              {% if order.tracking_data %}
                <div class="mt-2">
                  {% for tracking in order.tracking_data[:1] %}
                    <span class="badge bg-warning text-dark tracking-badge" title="运单号: {{ tracking.tracking_number }}">
                      <i class="fas fa-truck me-1"></i> {{ tracking.carrier_name }}
                    </span>
                  {% endfor %}
                  {% if order.tracking_data|length > 1 %}
                    <span class="badge bg-info tracking-badge">+{{ order.tracking_data|length - 1 }}</span>
                  {% endif %}
                </div>
              {% endif %}
            </td>
            <td>
              <div>
                {% if order.customer_email %}
                  <a href="/customer/{{ order.customer_email }}" style="color: #007bff; text-decoration: underline;">
                    {% if order.customer_first_name or order.customer_last_name %}
                      {{ order.customer_first_name }} {{ order.customer_last_name }}
                    {% else %}
                      {{ order.customer_name }}
                    {% endif %}
                  </a>
                {% else %}
                  {% if order.customer_first_name or order.customer_last_name %}
                    {{ order.customer_first_name }} {{ order.customer_last_name }}
                  {% else %}
                    {{ order.customer_name }}
                  {% endif %}
                {% endif %}
              </div>
              {% if order.customer_country %}
                <small class="text-muted"><i class="fas fa-flag me-1"></i> {{ order.customer_country | country_name }}</small>
              {% endif %}
            </td>
            <td class="text-center product-info-column">
              {% if order.items %}
                {% for item in order.items[:3] %}  <!-- 只显示前3个商品 -->
                  <div class="text-start">
                    <small>{{ item.name }}({% if item.meta_data %}{% for meta in item.meta_data %}{{ meta.value }}{% endfor %}{% endif %}) - {{ item.quantity }}</small>
                  </div>
                {% endfor %}
                {% if order.items|length > 3 %}
                  <div><small class="text-muted">+{{ order.items|length - 3 }} 更多</small></div>
                {% endif %}
              {% else %}
                <small class="text-muted">-</small>
              {% endif %}
            </td>
            <td class="text-center"><span class="badge bg-primary rounded-pill">{{ order.item_count }}</span></td>
            <td class="text-end">
              <strong class="text-success">{{ "%.2f"|format(order.total) }} {{ order.currency }}</strong>
            </td>
            <td class="text-center product-info-column">
              <small>{{ order.order_date.strftime('%Y-%m-%d %H:%M') if order.order_date else '-' }}</small>
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="fw-bold">{{ order.source }}</span>
                <small class="text-muted">{{ order.domain }}</small>
              </div>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    {% if pagination.pages > 1 %}
    <nav aria-label="订单分页" class="mt-4">
      <ul class="pagination justify-content-center">
        <!-- 上一页 -->
        {% if pagination.has_prev %}
          <li class="page-item">
            <a class="page-link" href="?page={{ pagination.prev_num }}&per_page={{ per_page }}" aria-label="上一页">
              <span aria-hidden="true">&laquo;</span>
            </a>
          </li>
        {% else %}
          <li class="page-item disabled">
            <span class="page-link">&laquo;</span>
          </li>
        {% endif %}

        <!-- 页码 -->
        {% for page_num in pagination.iter_pages() %}
          {% if page_num %}
            {% if page_num != pagination.page %}
              <li class="page-item">
                <a class="page-link" href="?page={{ page_num }}&per_page={{ per_page }}">{{ page_num }}</a>
              </li>
            {% else %}
              <li class="page-item active">
                <span class="page-link">{{ page_num }}</span>
              </li>
            {% endif %}
          {% else %}
            <li class="page-item disabled">
              <span class="page-link">…</span>
            </li>
          {% endif %}
        {% endfor %}

        <!-- 下一页 -->
        {% if pagination.has_next %}
          <li class="page-item">
            <a class="page-link" href="?page={{ pagination.next_num }}&per_page={{ per_page }}" aria-label="下一页">
              <span aria-hidden="true">&raquo;</span>
            </a>
          </li>
        {% else %}
          <li class="page-item disabled">
            <span class="page-link">&raquo;</span>
          </li>
        {% endif %}
      </ul>
    </nav>
    
    <!-- 分页信息 -->
    <div class="text-center text-muted mt-3">
      共 {{ total_orders }} 个订单，当前第 {{ pagination.page }} 页，共 {{ pagination.pages }} 页
    </div>
    {% endif %}

  </div>

  <!-- 客户详情模态框 -->
  <div class="modal fade" id="customerDetailsModal" tabindex="-1" aria-labelledby="customerDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" style="max-width: 960px;">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="customerDetailsModalLabel"><i class="fas fa-user me-2"></i>客户详情</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div id="customerDetailsContent">
            <!-- 客户详情将通过JavaScript动态加载 -->
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 商品详情模态框 -->
  <div class="modal fade" id="itemDetailsModal" tabindex="-1" aria-labelledby="itemDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" style="max-width: 960px;">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="itemDetailsModalLabel"><i class="fas fa-box me-2"></i>商品详情</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div id="itemDetailsContent">
            <!-- 商品详情将通过JavaScript动态加载 -->
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 定义国家代码到中文名称的映射
    const countryCodesToNames = {
      'AF': '阿富汗',
      'AX': '奥兰群岛',
      'AL': '阿尔巴尼亚',
      'DZ': '阿尔及利亚',
      'AS': '美属萨摩亚',
      'AD': '安道尔',
      'AO': '安哥拉',
      'AI': '安圭拉',
      'AQ': '南极洲',
      'AG': '安提瓜和巴布达',
      'AR': '阿根廷',
      'AM': '亚美尼亚',
      'AW': '阿鲁巴',
      'AU': '澳大利亚',
      'AT': '奥地利',
      'AZ': '阿塞拜疆',
      'BS': '巴哈马',
      'BH': '巴林',
      'BD': '孟加拉国',
      'BB': '巴巴多斯',
      'BY': '白俄罗斯',
      'BE': '比利时',
      'BZ': '伯利兹',
      'BJ': '贝宁',
      'BM': '百慕大',
      'BT': '不丹',
      'BO': '玻利维亚',
      'BQ': '荷兰加勒比区',
      'BA': '波斯尼亚和黑塞哥维那',
      'BW': '博茨瓦纳',
      'BV': '布韦岛',
      'BR': '巴西',
      'IO': '英属印度洋领地',
      'BN': '文莱',
      'BG': '保加利亚',
      'BF': '布基纳法索',
      'BI': '布隆迪',
      'CV': '佛得角',
      'KH': '柬埔寨',
      'CM': '喀麦隆',
      'CA': '加拿大',
      'KY': '开曼群岛',
      'CF': '中非共和国',
      'TD': '乍得',
      'CL': '智利',
      'CN': '中国',
      'CX': '圣诞岛',
      'CC': '科科斯（基林）群岛',
      'CO': '哥伦比亚',
      'KM': '科摩罗',
      'CG': '刚果（布）',
      'CD': '刚果（金）',
      'CK': '库克群岛',
      'CR': '哥斯达黎加',
      'CI': '科特迪瓦',
      'HR': '克罗地亚',
      'CU': '古巴',
      'CW': '库拉索',
      'CY': '塞浦路斯',
      'CZ': '捷克',
      'DK': '丹麦',
      'DJ': '吉布提',
      'DM': '多米尼克',
      'DO': '多米尼加共和国',
      'EC': '厄瓜多尔',
      'EG': '埃及',
      'SV': '萨尔瓦多',
      'GQ': '赤道几内亚',
      'ER': '厄立特里亚',
      'EE': '爱沙尼亚',
      'ET': '埃塞俄比亚',
      'FK': '福克兰群岛',
      'FO': '法罗群岛',
      'FJ': '斐济',
      'FI': '芬兰',
      'FR': '法国',
      'GF': '法属圭亚那',
      'PF': '法属波利尼西亚',
      'TF': '法属南方和南极领地',
      'GA': '加蓬',
      'GM': '冈比亚',
      'GE': '格鲁吉亚',
      'DE': '德国',
      'GH': '加纳',
      'GI': '直布罗陀',
      'GR': '希腊',
      'GL': '格陵兰',
      'GD': '格林纳达',
      'GP': '瓜德罗普',
      'GU': '关岛',
      'GT': '危地马拉',
      'GG': '根西',
      'GN': '几内亚',
      'GW': '几内亚比绍',
      'GY': '圭亚那',
      'HT': '海地',
      'HM': '赫德岛和麦克唐纳群岛',
      'VA': '梵蒂冈',
      'HN': '洪都拉斯',
      'HK': '香港',
      'HU': '匈牙利',
      'IS': '冰岛',
      'IN': '印度',
      'ID': '印度尼西亚',
      'IR': '伊朗',
      'IQ': '伊拉克',
      'IE': '爱尔兰',
      'IM': '马恩岛',
      'IL': '以色列',
      'IT': '意大利',
      'JM': '牙买加',
      'JP': '日本',
      'JE': '泽西',
      'JO': '约旦',
      'KZ': '哈萨克斯坦',
      'KE': '肯尼亚',
      'KI': '基里巴斯',
      'KP': '朝鲜',
      'KR': '韩国',
      'KW': '科威特',
      'KG': '吉尔吉斯斯坦',
      'LA': '老挝',
      'LV': '拉脱维亚',
      'LB': '黎巴嫩',
      'LS': '莱索托',
      'LR': '利比里亚',
      'LY': '利比亚',
      'LI': '列支敦士登',
      'LT': '立陶宛',
      'LU': '卢森堡',
      'MO': '澳门',
      'MK': '北马其顿',
      'MG': '马达加斯加',
      'MW': '马拉维',
      'MY': '马来西亚',
      'MV': '马尔代夫',
      'ML': '马里',
      'MT': '马耳他',
      'MH': '马绍尔群岛',
      'MQ': '马提尼克',
      'MR': '毛里塔尼亚',
      'MU': '毛里求斯',
      'YT': '马约特',
      'MX': '墨西哥',
      'FM': '密克罗尼西亚',
      'MD': '摩尔多瓦',
      'MC': '摩纳哥',
      'MN': '蒙古',
      'ME': '黑山',
      'MS': '蒙特塞拉特',
      'MA': '摩洛哥',
      'MZ': '莫桑比克',
      'MM': '缅甸',
      'NA': '纳米比亚',
      'NR': '瑙鲁',
      'NP': '尼泊尔',
      'NL': '荷兰',
      'NC': '新喀里多尼亚',
      'NZ': '新西兰',
      'NI': '尼加拉瓜',
      'NE': '尼日尔',
      'NG': '尼日利亚',
      'NU': '纽埃',
      'NF': '诺福克岛',
      'MP': '北马里亚纳群岛',
      'NO': '挪威',
      'OM': '阿曼',
      'PK': '巴基斯坦',
      'PW': '帕劳',
      'PS': '巴勒斯坦',
      'PA': '巴拿马',
      'PG': '巴布亚新几内亚',
      'PY': '巴拉圭',
      'PE': '秘鲁',
      'PH': '菲律宾',
      'PN': '皮特凯恩群岛',
      'PL': '波兰',
      'PT': '葡萄牙',
      'PR': '波多黎各',
      'QA': '卡塔尔',
      'RE': '留尼汪',
      'RO': '罗马尼亚',
      'RU': '俄罗斯',
      'RW': '卢旺达',
      'BL': '圣巴泰勒米',
      'SH': '圣赫勒拿、阿森松和特里斯坦-达库尼亚',
      'KN': '圣基茨和尼维斯',
      'LC': '圣卢西亚',
      'MF': '法属圣马丁',
      'PM': '圣皮埃尔和密克隆',
      'VC': '圣文森特和格林纳丁斯',
      'WS': '萨摩亚',
      'SM': '圣马力诺',
      'ST': '圣多美和普林西比',
      'SA': '沙特阿拉伯',
      'SN': '塞内加尔',
      'RS': '塞尔维亚',
      'SC': '塞舌尔',
      'SL': '塞拉利昂',
      'SG': '新加坡',
      'SX': '荷属圣马丁',
      'SK': '斯洛伐克',
      'SI': '斯洛文尼亚',
      'SB': '所罗门群岛',
      'SO': '索马里',
      'ZA': '南非',
      'GS': '南乔治亚和南桑威奇群岛',
      'SS': '南苏丹',
      'ES': '西班牙',
      'LK': '斯里兰卡',
      'SD': '苏丹',
      'SR': '苏里南',
      'SJ': '斯瓦尔巴和扬马延',
      'SZ': '斯威士兰',
      'SE': '瑞典',
      'CH': '瑞士',
      'SY': '叙利亚',
      'TW': '台湾',
      'TJ': '塔吉克斯坦',
      'TZ': '坦桑尼亚',
      'TH': '泰国',
      'TL': '东帝汶',
      'TG': '多哥',
      'TK': '托克劳',
      'TO': '汤加',
      'TT': '特立尼达和多巴哥',
      'TN': '突尼斯',
      'TR': '土耳其',
      'TM': '土库曼斯坦',
      'TC': '特克斯和凯科斯群岛',
      'TV': '图瓦卢',
      'UG': '乌干达',
      'UA': '乌克兰',
      'AE': '阿联酋',
      'GB': '英国',
      'US': '美国',
      'UM': '美国本土外小岛屿',
      'UY': '乌拉圭',
      'UZ': '乌兹别克斯坦',
      'VU': '瓦努阿图',
      'VE': '委内瑞拉',
      'VN': '越南',
      'VG': '英属维尔京群岛',
      'VI': '美属维尔京群岛',
      'WF': '瓦利斯和富图纳',
      'EH': '西撒哈拉',
      'YE': '也门',
      'ZM': '赞比亚',
      'ZW': '津巴布韦'
    };

    // 获取国家中文名称的函数
    function getCountryName(countryCode) {
      if (!countryCode) return '-';
      return countryCodesToNames[countryCode.toUpperCase()] || countryCode;
    }

    // 搜索和筛选功能
    let searchTimeout;

    function filterOrders() {
      // Show loading state
      const tbody = document.querySelector('tbody');
      tbody.innerHTML = '<tr><td colspan="7" class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></td></tr>';
      
      // Clear previous timeout
      clearTimeout(searchTimeout);
      
      // Set new timeout to avoid frequent requests
      searchTimeout = setTimeout(() => {
        const orderId = document.getElementById('searchOrderId').value;
        const country = document.getElementById('searchCountry').value;  // 改为国家筛选
        const source = document.getElementById('searchSource').value;
        const status = document.getElementById('searchStatus').value;
        
        // Build query parameters
        const params = new URLSearchParams();
        if (orderId) params.append('order_id', orderId);
        if (country) params.append('country', country);  // 改为国家参数
        if (source) params.append('source', source);
        if (status) params.append('status', status);
        
        // Send API request with authentication
        fetch(`/api/orders?${params.toString()}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'Authorization': 'Basic ' + btoa('admin:admin')
          }
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
          })
          .then(data => {
            updateOrderTable(data.orders);
            // Update order count display in title
            const titleElement = document.querySelector('h1.mb-0');
            if (titleElement) {
              const baseTitle = '📦 订单中心';
              titleElement.innerHTML = `<i class="fas fa-boxes me-3"></i>${baseTitle}（共 ${data.count} 个订单）`;
            }
            
            // Update status stat cards
            if (data.status_counts) {
              updateStatusStatsFromAPI(data.status_counts);
            } else {
              updateStatusStats(data.orders);
            }
            
            // 更新已退款订单统计
            if (data.refunded_orders_count !== undefined) {
              const refundedCountElement = document.getElementById('refundedOrderCount');
              if (refundedCountElement) {
                refundedCountElement.textContent = data.refunded_orders_count;
              }
            }
          })
          .catch(error => {
            console.error('Search error:', error);
            tbody.innerHTML = '<tr><td colspan="7" class="text-center text-danger">加载数据出错，请稍后重试</td></tr>';
          });
      }, 300); // 300ms delay
    }

    function clearFilter() {
      document.getElementById('searchOrderId').value = '';
      document.getElementById('searchCountry').value = '';  // 改为国家筛选
      document.getElementById('searchSource').value = '';
      document.getElementById('searchStatus').value = '';
      
      // Reload all orders
      filterOrders();
    }

    function updateStatusStats(orders) {
      // Count orders by status
      const statusCounts = {};
      orders.forEach(order => {
        const statusKey = order.status;
        statusCounts[statusKey] = (statusCounts[statusKey] || 0) + 1;
      });
      
      // Update status stat cards
      const statusCards = document.querySelectorAll('.status-stat-card');
      statusCards.forEach(card => {
        const statusText = card.querySelector('.small').textContent.trim();
        let statusKey = '';
        
        // Map Chinese status text to status key
        if (statusText.includes('待处理')) statusKey = 'processing';
        else if (statusText.includes('已完成')) statusKey = 'completed';
        else if (statusText.includes('已取消')) statusKey = 'cancelled';
        else if (statusText.includes('已退款')) statusKey = 'refunded';
        else if (statusText.includes('发货中')) statusKey = 'on-hold';
        else if (statusText.includes('被拒收')) statusKey = 'failed';
        else statusKey = statusText;
        
        const count = statusCounts[statusKey] || 0;
        card.querySelector('.fs-2.fw-bold').textContent = count;
      });
    }

    function updateStatusStatsFromAPI(statusCounts) {
      // 处理API返回的状态计数
      const adjustedStatusCounts = {};
      for (const [status, count] of Object.entries(statusCounts)) {
        adjustedStatusCounts[status] = count;
      }
      
      // Update status stat cards
      const statusCards = document.querySelectorAll('.status-stat-card');
      statusCards.forEach(card => {
        const statusText = card.querySelector('.small').textContent.trim();
        let statusKey = '';
        
        // Map Chinese status text to status key
        if (statusText.includes('待处理')) statusKey = 'processing';
        else if (statusText.includes('已完成')) statusKey = 'completed';
        else if (statusText.includes('已取消')) statusKey = 'cancelled';
        else if (statusText.includes('已退款')) statusKey = 'refunded';
        else if (statusText.includes('发货中')) statusKey = 'on-hold';
        else if (statusText.includes('被拒收')) statusKey = 'failed';
        else statusKey = statusText;
        
        const count = adjustedStatusCounts[statusKey] || 0;
        card.querySelector('.fs-2.fw-bold').textContent = count;
      });
    }

    function updateOrderTable(orders) {
      const tbody = document.querySelector('tbody');
      tbody.innerHTML = '';
      
      if (orders.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted py-5"><i class="fas fa-inbox fa-2x mb-3 d-block"></i>暂无订单数据</td></tr>';
        return;
      }
      
      orders.forEach(order => {
        const row = document.createElement('tr');
        row.className = 'order-card';
        row.onclick = () => window.location.href = `/order/${order.id}`;
        
        // Format date
        const orderDate = order.order_date ? new Date(order.order_date).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          hour12: false
        }) : '-';
        
        // Status badge
        let statusBadge = '';
        switch(order.status) {
          case 'processing':
            statusBadge = '<span class="badge badge-pending"><i class="fas fa-clock me-1"></i> 待处理</span>';
            break;
          case 'completed':
            statusBadge = '<span class="badge badge-completed"><i class="fas fa-check-circle me-1"></i> 已完成</span>';
            break;
          case 'cancelled':
            statusBadge = '<span class="badge badge-cancelled"><i class="fas fa-times-circle me-1"></i> 已取消</span>';
            break;
          case 'refunded':
            statusBadge = '<span class="badge badge-refunded"><i class="fas fa-undo me-1"></i> 已退款</span>';
            break;
          case 'on-hold':
            statusBadge = '<span class="badge badge-on-hold"><i class="fas fa-pause-circle me-1"></i> 发货中</span>';
            break;
          case 'failed':
            statusBadge = '<span class="badge badge-failed"><i class="fas fa-exclamation-triangle me-1"></i> 被拒收</span>';
            break;
          default:
            statusBadge = `<span class="badge bg-secondary">${order.status}</span>`;
        }
        
        // 物流信息
        let trackingInfo = '';
        if (order.tracking_data && order.tracking_data.length > 0) {
          const firstTracking = order.tracking_data[0];
          trackingInfo = `
            <div class="mt-2">
              <span class="badge bg-warning text-dark tracking-badge" title="运单号: ${firstTracking.tracking_number}">
                <i class="fas fa-truck me-1"></i> ${firstTracking.carrier_name}
              </span>
              ${order.tracking_data.length > 1 ? `<span class="badge bg-info tracking-badge">+${order.tracking_data.length - 1}</span>` : ''}
            </div>
          `;
        }
        
        row.innerHTML = `
          <td class="text-center product-info-column">
              <strong>#${order.order_id}</strong>
            </td>
            <td class="text-center product-info-column">
              ${statusBadge}
              ${trackingInfo}
            </td>
            <td>
              <div>
                ${order.customer_email ? 
                  '<a href="/customer/' + order.customer_email + '" style="color: #007bff; text-decoration: underline;">' +
                    (order.customer_first_name || order.customer_last_name ? 
                      (order.customer_first_name + ' ' + order.customer_last_name).trim() : 
                      order.customer_name) +
                  '</a>' : 
                  (order.customer_first_name || order.customer_last_name ? 
                    (order.customer_first_name + ' ' + order.customer_last_name).trim() : 
                    order.customer_name)}
              </div>
              ${order.customer_country ? 
                '<small class="text-muted"><i class="fas fa-flag me-1"></i> ' + getCountryName(order.customer_country) + '</small>' : 
                ''}
            </td>
            <td class="text-center product-info-column">
              ${order.items && order.items.length > 0 ? 
                order.items.slice(0, 3).map(item => {
                  let itemHtml = '<div class="text-start"><small>' + item.name;
                  if (item.meta_data && item.meta_data.length > 0) {itemHtml += ' (' + item.meta_data.map(meta => meta.value).join(') (') + ')';}
                  itemHtml += '</div>';
                  return itemHtml;
                }).join('') + 
                (order.items.length > 3 ? '<div><small class="text-muted">+' + (order.items.length - 3) + ' 更多</small></div>' : '') : 
                '<small class="text-muted">-</small>'}
            </td>
            <td class="text-center"><span class="badge bg-primary rounded-pill">${order.item_count}</span></td>
            <td class="text-end">
              <strong class="text-success">${parseFloat(order.total).toFixed(2)} ${order.currency}</strong>
            </td>
            <td class="text-center product-info-column">
              <small>${orderDate}</small>
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="fw-bold">${order.source}</span>
                <small class="text-muted">${order.domain}</small>
              </div>
            </td>
          `;
        
        tbody.appendChild(row);
      });
      
      // Rebind modal events
      bindModalEvents();
    }

    function bindModalEvents() {
      // 重新绑定客户详情模态框事件
      const customerDetailsModal = document.getElementById('customerDetailsModal');
      if (customerDetailsModal) {
        const newCustomerDetailsModal = customerDetailsModal.cloneNode(true);
        customerDetailsModal.parentNode.replaceChild(newCustomerDetailsModal, customerDetailsModal);
        
        newCustomerDetailsModal.addEventListener('show.bs.modal', function (event) {
          // 获取触发按钮
          const button = event.relatedTarget;
          
          // 获取客户详情数据
          const customerFirstName = button.getAttribute('data-customer-first-name') || '-';
          const customerLastName = button.getAttribute('data-customer-last-name') || '-';
          const customerName = button.getAttribute('data-customer-name') || '-';
          const customerEmail = button.getAttribute('data-customer-email') || '-';
          const customerPhone = button.getAttribute('data-customer-phone') || '-';
          const customerAddress = button.getAttribute('data-customer-address') || '-';
          const customerAddress2 = button.getAttribute('data-customer-address-2') || '';
          const customerCity = button.getAttribute('data-customer-city') || '-';
          const customerState = button.getAttribute('data-customer-state') || '-';
          const customerPostcode = button.getAttribute('data-customer-postcode') || '-';
          const customerCountry = getCountryName(button.getAttribute('data-customer-country')) || '-';
          
          // 生成客户姓名显示
          let displayName = customerName;
          if (customerFirstName !== '-' || customerLastName !== '-') {
            displayName = (customerFirstName !== '-' ? customerFirstName : '') + 
                         (customerLastName !== '-' ? ' ' + customerLastName : '');
            displayName = displayName.trim() || customerName;
          }
          
          // 生成客户详情HTML
          let html = `
            <div class="row">
              <div class="col-md-6">
                <h5><i class="fas fa-user me-2"></i>基本信息</h5>
                <table class="table table-borderless">
                  <tr>
                    <td><strong>客户姓名:</strong></td>
                    <td>${displayName}</td>
                  </tr>
                  <tr>
                    <td><strong>名 (First Name):</strong></td>
                    <td>${customerFirstName !== '-' ? customerFirstName : '-'}</td>
                  </tr>
                  <tr>
                    <td><strong>姓 (Last Name):</strong></td>
                    <td>${customerLastName !== '-' ? customerLastName : '-'}</td>
                  </tr>
                  <tr>
                    <td><strong>电子邮件:</strong></td>
                    <td>${customerEmail}</td>
                  </tr>
                  <tr>
                    <td><strong>联系电话:</strong></td>
                    <td>${customerPhone}</td>
                  </tr>
                </table>
              </div>
              <div class="col-md-6">
                <h5><i class="fas fa-map-marker-alt me-2"></i>地址信息</h5>
                <table class="table table-borderless">
                  <tr>
                    <td><strong>地址:</strong></td>
                    <td>${customerAddress}</td>
                  </tr>
                  ${customerAddress2 ? `<tr>
                    <td><strong>InPost:</strong></td>
                    <td>${customerAddress2}</td>
                  </tr>` : ''}
                  <tr>
                    <td><strong>城市:</strong></td>
                    <td>${customerCity}</td>
                  </tr>
                  <tr>
                    <td><strong>州/省:</strong></td>
                    <td>${customerState}</td>
                  </tr>
                  <tr>
                    <td><strong>邮编:</strong></td>
                    <td>${customerPostcode}</td>
                  </tr>
                  <tr>
                    <td><strong>国家:</strong></td>
                    <td>${customerCountry}</td>
                  </tr>
                </table>
              </div>
            </div>
          `;
          
          // 显示客户详情
          document.getElementById('customerDetailsContent').innerHTML = html;
        });
      }
      
      // 重新绑定商品详情模态框事件
      const itemDetailsModal = document.getElementById('itemDetailsModal');
      if (itemDetailsModal) {
        const newItemDetailsModal = itemDetailsModal.cloneNode(true);
        itemDetailsModal.parentNode.replaceChild(newItemDetailsModal, itemDetailsModal);
        
        newItemDetailsModal.addEventListener('show.bs.modal', function (event) {
          // 获取触发按钮
          const button = event.relatedTarget;
          // 获取商品详情数据
          const itemDetailsJson = button.getAttribute('data-item-details');
          
          // 解析商品详情
          let items = [];
          try {
            items = JSON.parse(itemDetailsJson);
          } catch (e) {
            console.error('解析商品详情失败:', e);
            document.getElementById('itemDetailsContent').innerHTML = '<p class="text-danger">无法加载商品详情</p>';
            return;
          }
          
          // 生成商品详情HTML
          let html = '<div class="table-responsive"><table class="table table-striped">';
          html += '<thead><tr><th>商品名称</th><th>SKU</th><th>数量</th><th>单价</th><th>总价</th><th>属性</th></tr></thead><tbody>';
          
          items.forEach(item => {
            // 处理商品属性
            let attributes = '';
            if (item.meta_data && item.meta_data.length > 0) {
              attributes = item.meta_data.map(attr => 
                `${attr.display_key}: ${attr.display_value}`
              ).join('<br>');
            }
            
            html += `<tr>
              <td>${item.name || '-'}</td>
              <td>${item.sku || '-'}</td>
              <td>${item.quantity || 0}</td>
              <td>${parseFloat(item.price || 0).toFixed(2)}</td>
              <td>${parseFloat(item.total || 0).toFixed(2)}</td>
              <td>${attributes || '-'}</td>
            </tr>`;
          });
          
          html += '</tbody></table></div>';
          
          // 显示商品详情
          document.getElementById('itemDetailsContent').innerHTML = html;
        });
      }
    }

    // 滚动加载相关变量
    let isLoading = false;
    let currentPage = 1;
    let totalPages = 1;
    let hasMoreData = true;

    // 滚动加载函数
    function loadMoreOrders() {
      if (isLoading || !hasMoreData) return;
      
      isLoading = true;
      currentPage++;
      
      // 显示加载指示器
      const loadingIndicator = document.createElement('tr');
      loadingIndicator.innerHTML = '<td colspan="7" class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></td>';
      loadingIndicator.id = 'loading-indicator';
      document.querySelector('tbody').appendChild(loadingIndicator);
      
      // 构建查询参数
      const params = new URLSearchParams();
      params.append('page', currentPage);
      params.append('per_page', 20);
      
      // 获取当前筛选条件
      const orderId = document.getElementById('searchOrderId').value;
      const country = document.getElementById('searchCountry').value;  // 改为国家筛选
      const source = document.getElementById('searchSource').value;
      const status = document.getElementById('searchStatus').value;
      
      if (orderId) params.append('order_id', orderId);
      if (country) params.append('country', country);  // 改为国家参数
      if (source) params.append('source', source);
      if (status) params.append('status', status);
      
      // 发送Ajax请求
      fetch(`/api/orders?${params.toString()}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          'Authorization': 'Basic ' + btoa('admin:admin')
        }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        // 移除加载指示器
        const loadingIndicator = document.getElementById('loading-indicator');
        if (loadingIndicator) {
          loadingIndicator.remove();
        }
        
        // 更新分页信息
        totalPages = data.total_pages;
        hasMoreData = data.has_next;
        
        // 添加新数据到表格
        const tbody = document.querySelector('tbody');
        data.orders.forEach(order => {
          const row = document.createElement('tr');
          row.className = 'order-card';
          row.onclick = () => window.location.href = `/order/${order.id}`;
          
          // 格式化日期
          const orderDate = order.order_date ? new Date(order.order_date).toLocaleString('zh-CN') : '-';
          
          // 状态徽章
          let statusBadge = '';
          switch(order.status) {
            case 'processing':
              statusBadge = '<span class="badge badge-pending"><i class="fas fa-clock me-1"></i> 待处理</span>';
              break;
            case 'completed':
              statusBadge = '<span class="badge badge-completed"><i class="fas fa-check-circle me-1"></i> 已完成</span>';
              break;
            case 'cancelled':
              statusBadge = '<span class="badge badge-cancelled"><i class="fas fa-times-circle me-1"></i> 已取消</span>';
              break;
            case 'refunded':
              statusBadge = '<span class="badge badge-refunded"><i class="fas fa-undo me-1"></i> 已退款</span>';
              break;
            case 'on-hold':
              statusBadge = '<span class="badge badge-on-hold"><i class="fas fa-pause-circle me-1"></i> 发货中</span>';
              break;
            case 'failed':
              statusBadge = '<span class="badge badge-failed"><i class="fas fa-exclamation-triangle me-1"></i> 被拒收</span>';
              break;
            default:
              statusBadge = `<span class="badge bg-secondary">${order.status}</span>`;
          }
          
          // 物流信息
          let trackingInfo = '';
          if (order.tracking_data && order.tracking_data.length > 0) {
            const firstTracking = order.tracking_data[0];
            trackingInfo = `
              <div class="mt-2">
                <span class="badge bg-warning text-dark tracking-badge" title="运单号: ${firstTracking.tracking_number}">
                  <i class="fas fa-truck me-1"></i> ${firstTracking.carrier_name}
                </span>
                ${order.tracking_data.length > 1 ? `<span class="badge bg-info tracking-badge">+${order.tracking_data.length - 1}</span>` : ''}
              </div>
            `;
          }
          
          row.innerHTML = `
            <td class="text-center product-info-column">
              <strong>#${order.order_id}</strong>
            </td>
            <td class="text-center product-info-column">
              ${statusBadge}
              ${trackingInfo}
            </td>
            <td>
              <div>
                ${order.customer_email ? 
                  '<a href="/customer/' + order.customer_email + '" style="color: #007bff; text-decoration: underline;">' +
                    (order.customer_first_name || order.customer_last_name ? 
                      (order.customer_first_name + ' ' + order.customer_last_name).trim() : 
                      order.customer_name) +
                  '</a>' : 
                  (order.customer_first_name || order.customer_last_name ? 
                    (order.customer_first_name + ' ' + order.customer_last_name).trim() : 
                    order.customer_name)}
              </div>
              ${order.customer_country ? 
                '<small class="text-muted"><i class="fas fa-flag me-1"></i> ' + getCountryName(order.customer_country) + '</small>' : 
                ''}
            </td>
            <td class="text-center product-info-column">
              ${order.items && order.items.length > 0 ? 
                order.items.slice(0, 3).map(item => {
                  let itemHtml = '<div class="text-start"><small>' + item.name;
                  if (item.meta_data && item.meta_data.length > 0) {itemHtml += ' (' + item.meta_data.map(meta => meta.value).join(') (') + ')';}
                  itemHtml += '</div>';
                  return itemHtml;
                }).join('') + 
                (order.items.length > 3 ? '<div><small class="text-muted">+' + (order.items.length - 3) + ' 更多</small></div>' : '') : 
                '<small class="text-muted">-</small>'}
            </td>
            <td class="text-center"><span class="badge bg-primary rounded-pill">${order.item_count}</span></td>
            <td class="text-end">
              <strong class="text-success">${parseFloat(order.total).toFixed(2)} ${order.currency}</strong>
            </td>
            <td class="text-center product-info-column">
              <small>${orderDate}</small>
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="fw-bold">${order.source}</span>
                <small class="text-muted">${order.domain}</small>
              </div>
            </td>
          `;
          
          tbody.appendChild(row);
        });
      })
      .catch(error => {
        // 移除加载指示器
        const loadingIndicator = document.getElementById('loading-indicator');
        if (loadingIndicator) {
          loadingIndicator.remove();
        }
        
        console.error('加载更多订单失败:', error);
        // 显示错误信息
        const errorRow = document.createElement('tr');
        errorRow.innerHTML = '<td colspan="7" class="text-center text-danger">加载更多订单失败，请稍后重试</td>';
        document.querySelector('tbody').appendChild(errorRow);
        
        // 恢复加载状态
        isLoading = false;
      })
      .finally(() => {
        // 恢复加载状态
        isLoading = false;
      });
    }

    // 检查是否需要加载更多数据
    function checkScroll() {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const scrollHeight = document.documentElement.scrollHeight;
      const clientHeight = document.documentElement.clientHeight;
      
      // 当滚动到距离底部100px时加载更多数据
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadMoreOrders();
      }
    }

    // 手动同步订单
    function syncOrders() {
      if (confirm('确定要手动同步订单数据吗？这可能需要一些时间。')) {
        // 显示加载状态
        const syncBtn = event.target;
        const originalText = syncBtn.innerHTML;
        syncBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> 同步中...';
        syncBtn.disabled = true;
        
        // 发送同步请求
        fetch('/api/sync-orders', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'Authorization': 'Basic ' + btoa('admin:admin')
          }
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            if (data.stats) {
              alert('订单同步完成！新增 ' + data.stats.inserted + ' 个订单，更新 ' + data.stats.updated + ' 个订单');
            } else {
              alert('订单同步完成！' + (data.details || ''));
            }
            // 刷新页面以显示最新数据
            location.reload();
          } else {
            alert('同步失败: ' + data.error);
          }
        })
        .catch(error => {
          console.error('同步错误:', error);
          // 检查是否是Cloudflare防护相关的错误
          if (error.message && (error.message.includes('cloudflare') || error.message.includes('拦截'))) {
            alert('同步失败：请求被目标站点的安全防护拦截，请稍后重试。');
          } else {
            alert('同步过程中发生错误: ' + error.message);
          }
        })
        .finally(() => {
          // 恢复按钮状态
          syncBtn.innerHTML = originalText;
          syncBtn.disabled = false;
        });
      }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
      // 添加滚动事件监听器
      window.addEventListener('scroll', checkScroll);
      
      // 初始化已退款订单统计
      initializeRefundedOrderCount();
    });
    
    // 初始化已退款订单统计
    function initializeRefundedOrderCount() {
      // 发送请求获取已退款订单统计
      fetch('/api/orders?page=1&per_page=1', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          'Authorization': 'Basic ' + btoa('admin:admin')
        }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        if (data.refunded_orders_count !== undefined) {
          const refundedCountElement = document.getElementById('refundedOrderCount');
          if (refundedCountElement) {
            refundedCountElement.textContent = data.refunded_orders_count;
          }
        }
      })
      .catch(error => {
        console.error('获取已退款订单统计失败:', error);
      });
    }
  </script>
</body>
</html>